<template>
  <div class="home-container">
    <!-- 头部区域 -->
    <van-nav-bar fixed>
      <!-- 左侧的插槽 -->
      <template #left>
        <img src="../../assets/toutiao_logo.png" alt="logo" class="logo" />
      </template>
      <!-- 右侧的插槽 -->
      <template #right>
        <van-icon name="search" color="white" size="18" @click="$router.push('/search')" />
      </template>
    </van-nav-bar>
    <!-- 频道列表的标签页 -->
    <van-tabs v-model="active" sticky offset-top="1.22666667rem" :before-change="beforeTabsChange" @change="onTabsChange">
      <van-tab :title="item.name" v-for="item in userChannel" :key="item.id">
        <!-- 每个频道下都要有文章列表 -->
        <!-- 记住，在绑定组件属性的时候，推荐把小驼峰命名的属性，改成以短横线的方式 -->
        <art-list :channel-id="item.id"></art-list>
      </van-tab>
    </van-tabs>
    <!-- 频道管理图标 -->
    <van-icon name="plus" size="16" class="plus" @click="show=true"/>
    <!-- 频道管理的弹出层 -->
    <van-popup v-model="show" :close-on-click-overlay='false' @closed='isDel=false'>
      <div class="popup-container">

  <!-- 弹出层的头部区域 -->
  <van-nav-bar title="频道管理">
    <template #right>
      <van-icon name="cross" size="14" color="white" @click="show = false" />
    </template>
  </van-nav-bar>

  <!-- 弹出层的主体区域 -->
  <div class="pop-body">
    <!-- 我的频道 -->
    <div class="my-channel-box">
      <div class="channel-title">
        <div>
          <span class="title-bold">已添加频道：</span>
          <span class="title-gray">{{isDel?'点击移除频道':'点击进入频道'}}</span>
        </div>
        <span class="btn-edit" @click="isDel=!isDel">{{isDel?'完成':'编辑'}}</span>
      </div>
      <!-- 我的频道列表 -->
      <van-row type="flex">
        <van-col span="6" v-for="(item,index) in userChannel" :key="item.id">
          <!-- 用户的频道 Item 项 -->
          <div class="channel-item van-hairline--surround" @click="onUserChannelClick(item,index)">{{item.name}}
            <!-- 删除的图标 -->
        <van-badge color="transparent" class="cross-badge" v-if="isDel && item.id!==0 && userChannel.length>2">
          <template #content>
            <van-icon name="cross" class="badge-icon" color="#cfcfcf" size="12" />
          </template>
        </van-badge>
          </div>
        </van-col>
      </van-row>
    </div>

    <!-- 分隔线 -->
    <div class="van-hairline--top sp-line"></div>

    <!-- 更多频道 -->
    <div class="more-channel-box">
      <div class="channel-title">
        <div>
          <span class="title-bold">可添加频道：</span>
          <span class="title-gray">点击添加频道</span>
        </div>
      </div>
      <!-- 更多频道列表 -->
      <van-row type="flex">
        <van-col span="6" v-for="item in moreChannel" :key="item.id">
          <div class="channel-item van-hairline--surround" @click="addChannel(item)">{{item.name}}</div>
        </van-col>
      </van-row>
    </div>
  </div>
</div>

    </van-popup>
  </div>
</template>

<script>
// 1.按需导入接口
import { getUserChannelAPI, getAllChannelApi, updateUserChannelApi } from '@/api/homeApi.js'
// 导入component组件
import ArtList from '@/components/Artlist/Artlist.vue'
const indexToTop = {}
export default {
  name: 'Home',
  data () {
    return {
      active: 0,
      // 2 用户频道列表数据
      userChannel: [],
      // 全部列表的数据
      allChannel: [],
      // 控制弹出层显示与隐藏
      show: false,
      // 控制删除图标的显示隐藏
      isDel: false
    }
  },
  computed: {
    moreChannel () {
      // 定义空数组，存放没有关注的数据
      const arr = []

      this.allChannel.forEach(item => {
        // 判断当前item是否在已关注列表中
        // 如果不在，把item存到arr中
        const index = this.userChannel.findIndex(x => {
          if (x.id === item.id) {
            return true
          }
        })
        if (index === -1) {
          arr.push(item)
        }
      })
      return arr
    }
  },
  created () {
    // 4.调用方法
    this.initUserChannel()
    // 全部列表数据调用
    this.initAllChannel()
  },
  activated () {
    // 只要Home组件被激活。就读取top值
    window.scrollTo(0, this.$route.meta.top)
  },
  methods: {
    // 3初始化用户数据方法
    async initUserChannel () {
      const { data: res } = await getUserChannelAPI()
      if (res.message === 'OK') {
        this.userChannel = res.data.channels
      }
    },

   async initAllChannel () {
    const { data: res } = await getAllChannelApi()
    if (res.message === 'OK') {
      this.allChannel = res.data.channels
    }
    },
    // 更新用户频道列表数据，发送请求
   async updateUserChannel () {
  // 1.循环userChannnel每一项，创建一个新数组
      const channerArr = this.userChannel.map((item, index) => {
       return {
         id: item.id,
         seq: index + 1
       }
      }).filter(item =>
        item.id !== 0
      )
      // 发送请求
       const { data: res } = await updateUserChannelApi(channerArr)
       if (res.message === 'OK') {
        //  提示用户修改成功
         this.$notify({ type: 'success', message: '更新成功' })
       }
    },
    // 点击添加频道（格式{id，name}）
    addChannel (item) {
      this.userChannel.push(item)
      // 把最新的频道，更新到服务器
      this.updateUserChannel()
    },
    // 点击了用户频道按钮
    onUserChannelClick (channel, index) {
      if (this.isDel) {
        // 如果点击是推荐不用删除
        if (channel.id === 0) return
        // 如果剩下的频道数量小于等于2个，不让删除了，不发请求
        if (this.userChannel.length <= 2) return
        // 处于删除状态
        this.userChannel = this.userChannel.filter(item => item.id !== channel.id)
        // 把最新的频道，更新到服务器
       this.updateUserChannel()
      } else {
        // 普通点击
        this.active = index
        this.show = false
      }
    },
    // 切换频道时，记录索引和高度
    beforeTabsChange () {
      indexToTop[this.active] = window.scrollY
      console.log(indexToTop)
      return true
    },
    // 频道图标改变后，把高度重新赋值
    onTabsChange () {
      this.$nextTick(() => {
        window.scrollTo(0, indexToTop[this.active] || 0)
      })
    }
  },
  components: {
    ArtList
  }
}
</script>

<style lang="less" scoped>
// 组件外层容器的样式
.home-container {
  padding-top: 46px;
  padding-bottom: 50px;
}
// logo 样式
.logo {
  height: 80%;
}
// 为 tabs 容器设置右 margin
/deep/.van-tabs__wrap {
  padding-right: 36px;
  background-color: white;
}
// 频道管理小图标的定位
.plus {
  position: fixed;
  top: 58px;
  right: 10px;
  z-index: 999;
}
.van-popup,
.popup-container {
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.popup-container {
  display: flex;
  flex-direction: column;
}

.pop-body {
  flex: 1;
  overflow: scroll;
  padding: 8px;
  background-color: white;
}

.my-channel-box,
.more-channel-box {
  .channel-title {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    line-height: 28px;
    padding: 0 6px;
    .title-bold {
      font-weight: bold;
    }
    .title-gray {
      color: gray;
      font-size: 12px;
    }
  }
}

.btn-edit {
  border: 1px solid #a3a2a2;
  padding: 0 10px;
  line-height: 20px;
  height: 20px;
  border-radius: 6px;
  font-size: 12px;
}

.channel-item {
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  background-color: #fafafa;
  margin: 6px;
}

.cross-badge {
  position: absolute;
  right: -3px;
  top: 0;
  border: none;
}

.sp-line {
  margin: 10px 0 20px 0;
}

</style>
